package com.mofish.zbserver.user.register;

import javax.annotation.Resource;

import com.mofish.zbserver.common.Constants;
import com.mofish.zbserver.common.model.role.Role;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mofish.zbserver.common.Result;
import com.mofish.zbserver.common.Utils;
import com.mofish.zbserver.common.model.user.User;

@RestController
@RequestMapping("/user/register")
public class RegisterAPI {
	@Resource
	private RegisterService registerService;

	/**
	 * 注册
	 * @param registerDto 包含用户的注册昵称、email、密码
	 * @return 成功注册返回用户uid，失败返回fail
	 */
	@PostMapping("")
	public Result register(@RequestBody RegisterDto registerDto) {

		try {
			if (registerService.getUserCountByU_name(registerDto.getU_name()) > 0) {
				return Result.fail(Result.ERR_CODE_BUSINESS, "昵称已被占用！");
			}

			if (registerService.getUserCountByU_email(registerDto.getU_email()) > 0) {
				return Result.fail(Result.ERR_CODE_BUSINESS, "该邮箱已被注册！");
			}

			// 获取新的用户ID
			String u_id = registerService.getUserNewU_id();

			User user = new User();
			user.setU_id(u_id);
			user.setU_email(registerDto.getU_email());
			user.setU_pwd(Utils.pwdtool(registerDto.getU_pwd()));
			user.setU_name(registerDto.getU_name());
			user.setU_reg(Utils.getNow());
			user.setR_id(Role.RID_COMMON_USER);
			user.setU_avatar(Constants.DEFAULT_AVATAR);

			registerService.addUser(user);
			return Result.success("注册成功！", u_id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.fail(Result.ERR_CODE_BUSINESS, "系统错误！注册失败！");
		}
	}
}
